package org.dreamwork.jasmine2.sample.converter;

import org.dreamwork.util.ICollection;
import org.dreamwork.util.IXMLConverter;
import org.dreamwork.util.NodeConverter;
import org.dreamwork.util.StringUtil;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by IntelliJ IDEA.
 * User: seth.yang
 * Date: 11-8-8
 * Time: 上午11:45
 */
public class MapConverter implements IXMLConverter<Map<String, String>> {
    public Map<String, String> convert (Class<Map<String, String>> type, Node node) {
        NodeList list = ((Element) node).getElementsByTagName ("entry");
        Map<String, String> map = new HashMap<String, String> ();
        for (int i = 0; i < list.getLength (); i ++) {
            Element e = (Element) list.item (i);
            String key = e.getAttribute ("key");
            String value = e.getAttribute ("value");
            map.put (key, value);
        }
        return map;
    }

    public void convert (Class<Map<String, String>> type, Map<String, String> bean, Node parent) {
        Document doc = parent.getOwnerDocument ();
        for (String key : bean.keySet ()) {
            Element e = doc.createElement ("entry");
            String value = bean.get (key);
            e.setAttribute ("key", key);
            e.setAttribute ("value", value);
            parent.appendChild (e);
        }
    }
}